package ch.quantasy.android.digest;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * This class helps to digest one-way-function any message. It can be done with
 * MD5 or with SHA-1.
 * 
 * It is equivalent to the function sha1sum in linux.
 * 
 * @author reto
 * 
 */
public class DigestHelper {
	public static BigInteger getMD5(final String message) {
		BigInteger messageDigest = null;
		try {
			final MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(message.getBytes());
			messageDigest = new BigInteger(1, digest.digest());

		} catch (final NoSuchAlgorithmException e) {
			// Not possible
		}
		return messageDigest;
	}

	public static BigInteger getSHA1(final String message) {
		BigInteger messageDigest = null;
		try {
			final MessageDigest digest = java.security.MessageDigest
					.getInstance("SHA-1");
			digest.update(message.getBytes());
			messageDigest = new BigInteger(1, digest.digest());

		} catch (final NoSuchAlgorithmException e) {
			// Not possible
		}
		return messageDigest;
	}

	public static String byteToString(final byte[] b) {
		final StringBuffer s = new StringBuffer();
		if (b == null) {
			return s.toString();
		}
		for (final byte element : b) {
			int d = element;
			d += d < 0 ? 256 : 0;
			// byte 128-255
			if (d < 16) {
				// 0-15 16
				s.append("0");
			}
			s.append(Integer.toString(d, 16));
		}
		return s.toString();
	}

	public static boolean isEqual(final String message,
			final BigInteger messageDigest) {
		return DigestHelper.getMD5(message).equals(messageDigest)
				|| DigestHelper.getSHA1(message).equals(messageDigest);
	}

}
